package handler

import (
	"context"
	"errors"
	"google.golang.org/protobuf/types/known/emptypb"
	"sale_system/goods_srv/global"
	"sale_system/goods_srv/model"
	"sale_system/goods_srv/proto"
)

// 轮播图接口

func (s *GoodsServer) BannerList(ctx context.Context, request *emptypb.Empty) (*proto.BannerListResponse, error) {

	var banners []model.Banner
	result := global.DB.Find(&banners)
	if result.Error != nil {
		return nil, result.Error
	}
	rsp := proto.BannerListResponse{}
	rsp.Total = int32(result.RowsAffected)

	for _, banner := range banners {

		bannerInfo := &proto.BannerResponse{
			Id:    banner.ID,
			Image: banner.Image,
			Index: banner.Index,
			Url:   banner.URL,
		}
		rsp.Data = append(rsp.Data, bannerInfo)
	}

	return &rsp, nil
}

func (s *GoodsServer) CreateBanner(ctx context.Context, request *proto.BannerRequest) (*proto.BannerResponse, error) {
	banner := model.Banner{}
	// 轮播图不需要查询存在
	banner.Image = request.Image
	banner.Index = request.Index
	banner.URL = request.Url

	global.DB.Create(&banner)

	return &proto.BannerResponse{Id: banner.ID}, nil
}

func (s *GoodsServer) DeleteBanner(ctx context.Context, request *proto.BannerRequest) (*emptypb.Empty, error) {

	result := global.DB.First(&model.Banner{}, request.Id)
	if result.RowsAffected == 0 {
		return &emptypb.Empty{}, errors.New("轮播图不存在")
	}
	result = global.DB.Delete(&model.Banner{}, request.Id)
	if result.RowsAffected == 0 {
		return &emptypb.Empty{}, errors.New("删除失败")
	}

	return &emptypb.Empty{}, nil
}

func (s *GoodsServer) UpdateBanner(ctx context.Context, request *proto.BannerRequest) (*emptypb.Empty, error) {

	banner := model.Banner{}
	result := global.DB.First(&banner, request.Id)
	if result.RowsAffected == 0 {
		return &emptypb.Empty{}, errors.New("轮播图不存在")
	}

	if banner.Image != "" {
		banner.Image = request.Image
	}

	if banner.Index != 0 {
		banner.Index = request.Index
	}

	if banner.URL != "" {
		banner.URL = request.Url
	}

	global.DB.Save(&banner)
	return &emptypb.Empty{}, nil
}
